from fastapi import APIRouter, Query,BackgroundTasks
from tortoise.expressions import Q,F
from app.controllers.appointment.list import appointment_list_controller
from app.schemas.appointment import AppointmentListUpdate, AppointmentListCreate
from app.schemas.base import Success, SuccessExtra,Fail
from app.settings import settings
from app.controllers.appointment.space import appointment_space_controller
from app.models.appointment import AppointmentList, AppointmentSalon
from app.utils.excel import create_excel,date_format
from fastapi.responses import JSONResponse

appointment_list_router = APIRouter()
model_name = "预约"


@appointment_list_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        type: int  = Query(None, description="大类"),
        d_type: int  = Query(None, description="小类"),
        space_id: int  = Query(None, description="门店id"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        customer_id=Query(0, description="用户id"),
):
    q = Q()
    if customer_id:
        user_id = customer_id
        q &= Q(user_id=user_id)
    if type:
        q &= Q(type=type)
    if d_type:
        q &= Q(type=d_type)
    if space_id:
        q &= Q(space_id=space_id)
    if start_time and end_time:
        q &= Q(time__range=[start_time, end_time])
    elif start_time:
        q &= Q(time__gte=start_time)
    elif end_time:
        q &= Q(time__lte=end_time)
    total, data = await appointment_list_controller.do_list(page=page, page_size=page_size, search=q)
    space_objs = await appointment_space_controller.level_list()

    for item in data:
        item['type_name'] = settings.APPOINTMENT_T[item['type']]
        if item['d_type']>0:
            item['d_type_name'] = settings.APPOINTMENT_TYPE[item['d_type']]
        else:
            item['d_type_name'] = "无"
        if item['space_id']>0:
            item['space_name'] = space_objs[item['space_id']]
        else:
            item['space_name'] = "无"
        item['status_name'] = settings.APPOINTMENT_STATUS[item['status']]
        if item['designer_names']:
            item['designer_name_s'] = ", ".join(item['designer_names'])
        else:
            item['designer_name_s'] = ""
        if item['ex_project_names']:
            item['ex_names'] = ", ".join(item['ex_project_names'])
            item['project_name_s'] = f"{item['project_name']}({item['ex_names']})"
        else:
            item['ex_names']=""
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@appointment_list_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await appointment_list_controller.do_detail(data_id=data_id)
    return Success(data=data)

@appointment_list_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        data_in: AppointmentListCreate,
):
    await appointment_list_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@appointment_list_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        data_in: AppointmentListUpdate,
):
    ##查到原来不是驳回状态的,如果改了沙龙驳回,沙龙字段number_have要减少1
    appointment = await AppointmentList.filter(id=data_in.id).first().values("status")
    num = appointment['status']
    if num != 2 and data_in.status ==2 and data_in.type==3:
        await AppointmentSalon.filter(id=data_in.project_id).update(number_have=F('number_have') - 1)
    if num == 2 and data_in.status ==1 and data_in.type==3:
        await AppointmentSalon.filter(id=data_in.project_id).update(number_have=F('number_have') + 1)
    await appointment_list_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@appointment_list_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await appointment_list_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@appointment_list_router.get("/type", summary="获取预约大类")
async def list_type():
    level_objs = settings.APPOINTMENT_T
    data = []
    key = 0
    for level in level_objs:
        if level:
            data.append({"label":level,"value":key})
        key += 1
    return Success(data=data)

@appointment_list_router.get("/excel", summary="导出数据")
async def list_excel(
        back_tasks: BackgroundTasks,
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    q = Q()
    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)
    space_objs = await appointment_space_controller.level_list()
    name = f"预约数据{start_time}~{end_time}"
    data = await AppointmentList.filter(q).all().select_related("parent").values(
        预约大类='type',
        预约子类='d_type',
        预约时间='time',
        门店="space_id",
        设计师="designer_names",
        项目名称="project_name",
        用户="user_name",
        用户卡号="user_card_no",
        审核状态="status",
    )

    for item in data:
        item["预约时间"] = date_format(item["预约时间"])
        item['预约大类'] = settings.APPOINTMENT_T[item['预约大类']]
        item['预约子类'] = settings.APPOINTMENT_TYPE[item['预约子类']]
        if item['门店']>0:
            item['门店'] = space_objs[item['门店']]
        item['审核状态'] = settings.APPOINTMENT_STATUS[item['审核状态']]

    back_tasks.add_task(create_excel, name=name,data=data)
    return JSONResponse(content={"code": 200, "message": "开始生成excel,请去下载中心查看"}, status_code=200)




